package cn.edu.hqu.exp.courseselection.web;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import cn.edu.hqu.exp.courseselection.domain.Course;
import cn.edu.hqu.exp.courseselection.domain.Course.Type;
import cn.edu.hqu.exp.courseselection.domain.ElectionForm;
import cn.edu.hqu.exp.courseselection.domain.PersonInfo;
import lombok.extern.slf4j.Slf4j;

@SessionAttributes(value="electionform")
@Slf4j
@Controller
@RequestMapping("/course")
public class CourseSeletionController {
	@ModelAttribute
	public void setCourse(Model model) {
		List<Course> courses = Arrays.asList(
				new Course(1,"JavaWeb开发技术",Type.Election),
				new Course(2,"数据挖掘",Type.Election),
				new Course(3,"计算机网络",Type.Core),
				new Course(4,"高等数学",Type.Basic),
				new Course(5,"影视精品分析与创作",Type.GeneralEle),
				new Course(6,"先秦诸子十五讲",Type.GeneralEle),
				new Course(7,"植物的艺术",Type.GeneralEle),
				new Course(8,"科幻小说阅读与赏析",Type.GeneralEle),
				new Course(9,"算法设计与分析",Type.Election),
				new Course(10,"数据挖掘",Type.Election),
				new Course(11,"软件工程",Type.Core),
				new Course(12,"计算机操作系统",Type.Core),
				new Course(13,"计算机组成原理",Type.Core),
				new Course(14,"大学物理",Type.Basic),
				new Course(15,"离散数学",Type.Basic),
				new Course(16,"高等代数",Type.Basic),
				new Course(17,"毛泽东思想与中国特色社会主义理论",Type.GeneralEdu),
				new Course(18,"马克思主义基本原理概论",Type.GeneralEdu),
				new Course(19,"职业生涯规划",Type.GeneralEdu),
				new Course(20,"形势与政策",Type.GeneralEdu)
		);
		Type[] types = Course.Type.values();
		model.addAttribute("types", types);
		for (Type type : types) {
		  model.addAttribute(type.toString(),
		      filterByType(courses, type));
		}
	}
	
	@GetMapping
	public String course(Model model) {
		model.addAttribute("electionform", new ElectionForm());
		return "course";
	}
	
	@PostMapping
	public String  processCourse(@Valid @ModelAttribute("electionform") ElectionForm course,Model model, Errors errors) {
		if(errors.hasErrors()) {
			return "course";
		}
		log.info("已选课程: " + course);
		return "redirect:/conclude";
	}
	
	private List<Course> filterByType(List<Course> courses, Type type){
		return courses.stream()
				.filter(x -> x.getType().equals(type))
				.collect(Collectors.toList());
	}
}
